const tagsEl = document.getElementById("tags");
const textarea = document.getElementById("textarea");

textarea.addEventListener("keyup", function (e) {
    createTags(e.target.value);
    if (e.key == "Enter") {
        randomSelect();
        textarea.value="";
    }
})

function createTags(value) {
    const tags = value.split("，").map(tag => tag.trim()).filter(tag => tag !== "");
    tagsEl.innerText = "";
    tags.forEach(tag => {
        const tagEl = document.createElement("span");
        tagEl.classList.add("tag");
        tagEl.innerText = tag;
        tagsEl.appendChild(tagEl);
    });
}

function randomSelect() {
    const interval = setInterval(() => {
        const randomTag = pickRandomTag();
        if (randomTag !== undefined) {
            highLightTag(randomTag);
            setTimeout(() => {
                unHighLightTag(randomTag);
            }, 100)
        }
    }, 100);
    const times = document.querySelectorAll(".tag").length * 5;
    setTimeout(() => {
        clearInterval(interval);
        setTimeout(() => {
            const randomTag = pickRandomTag();
            if (randomTag !== undefined){
                highLightTag(randomTag);
            }
        }, 100);
    }, times * 100);

}

function pickRandomTag() {
    const tags = document.querySelectorAll(".tag");
    if (tags[parseInt(Math.random() * tags.length)] == undefined) {
        alert("请正确输入")
    }
    return tags[parseInt(Math.random() * tags.length)];
}
function highLightTag(value) {
    value.classList.add("highlight");
}
function unHighLightTag(value) {
    value.classList.remove("highlight");
}